<script setup>
import { ref } from 'vue';
// 对话框可见状态
const dialogVisible = ref(false);
// 识别结果数据
const recognitionResult = ref({
  studentId: '',
  name: '',
  score: '',
  timeTaken: '',
  coverImg: '',
  categoryId: ''
});
//导入api中的userUploadImgService
import { userUploadImgService } from '@/api/score.js';

// 上传前处理函数
const beforeUpload = async (file) => {
  try {
    // 调用api上传图片
    const result = await userUploadImgService(file);
    // 将识别结果数据存储到 recognitionResult 中
    recognitionResult.value = result.data;
    // 显示对话框
    dialogVisible.value = true;
  } catch (error) {
    console.error('Error uploading image:', error.message);
  }
}


//导入score.js中的scoreAddService接口
import { scoreAddService } from '@/api/score.js';
//导入提示框组件
import { ElMessage } from 'element-plus'
// 确认添加按钮点击事件处理函数
const addLoadScore = async () => {
  try {
    // 调用接口将识别信息保存到数据库中
    let result = await scoreAddService(recognitionResult.value);
    //提示添加成功
    ElMessage.success('添加成功');
    // await saveToDatabase(recognitionResult.value);
    //清空识别结果数据
    recognitionResult.value = {
      studentId: '',
      name: '',
      score: '',
      timeTaken: '',
      coverImg: '',
      categoryId: ''
    };
  } catch (error) {
    console.error('Error saving to database:', error.message);
  }
}
//导入token
import { useTokenStore } from '@/stores/token.js'
const tokenStore = useTokenStore();
//上传成功回调函数
const uploadSuccess = (result) => {
  recognitionResult.value.coverImg = result.data;
    console.log(result);

}
import {Plus} from '@element-plus/icons-vue'

//文章分类数据模型
const categorys = ref([
    {
        "id": '',
        "categoryName": "",
        "categoryAlias": "",
        "createTime": "",
        "updateTime": ""
    }
])

//文章列表数据模型
const articles = ref([
    {
        "id": 1,
        "title": "",
        "content": "",
        "coverImg": "",
        "state": "",
        "categoryId": 2,
        "createTime": "",
        "updateTime": "",
        "studentId": '',
        "name": '',
        "score": '',
        "timeTaken": ''
    }
   
])

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(3)//每页条数


//调用article.js后台接口
import {articleCategoryListService,articleListeService} from '@/api/article.js'
const articleCategoryList =async()=>{
    let result = await articleCategoryListService();

    categorys.value = result.data
}
articleCategoryList();


//获取文章列表数据
const articleList = async()=>{
    let params = {
        pageNum:pageNum.value,
        pageSize:pageSize.value,
        categoryId:categoryId.value? categoryId.value : null,
        state:state.value? state.value : null
    }
   let result = await articleListeService(params);

   //渲染视图
   total.value = result.data.total;
   articles.value = result.data.items;


   //处理数据,给数据模型扩展一个属性categoryName，分类名称
   for(let i=0;i<articles.value.length;i++){
    let article = articles.value[i];
        for(let j=0;j<categorys.value.length;j++){
           if(article.categoryId == categorys.value[j].id) {
            article.categoryName = categorys.value[j].categoryName
           }
        }
   }
}
articleList();
</script>

<template>

    <el-row class="login-page">
        <el-col :span="10" class="bg"></el-col>
        <el-col :span="13" :offset="1" class="form">
    <el-card class="page-container">

          <!-- 上传图片区域 -->
    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                        action="/api/upload" 
                        :before-upload="beforeUpload"
                        name="file" 
                        :headers="{'Authorization':tokenStore.token}" 
                        :on-success="uploadSuccess">
                        <img v-if="recognitionResult.coverImg" :src="recognitionResult.coverImg" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <hr>
    <!-- 对话框 -->
        <template #header>
            <div class="header">
                <span><strong style="color: red;">通过上传图片自动识别信息</strong></span>
            </div>
        </template>
        
        <el-card class="page-container">
        <template #header>
            <div class="header">
                <strong style="color: green;"><span>识别结果</span></strong>
            </div>
        </template>

        <el-row>
            <el-col :span="12" class="score-form">
                <el-form :model="recognitionResult"  label-width="100px" size="large">

                    <el-form-item label="学号"> 
                        <el-input v-model="recognitionResult.studentId"  ></el-input>
                    </el-form-item>
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="recognitionResult.name"></el-input>
                    </el-form-item>
                    <el-form-item label="成绩" prop="score">
                        <el-input v-model="recognitionResult.score"></el-input>
                    </el-form-item>
                    <el-form-item label="作答时间" prop="timeTaken">
                        <el-input v-model="recognitionResult.timeTaken"></el-input>
                    </el-form-item>
                    <el-form-item label="成绩分类">
                    <el-select placeholder="请选择" v-model="recognitionResult.categoryId">
                        <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
                        </el-option>
                    </el-select>

                </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="addLoadScore">添加信息</el-button>
                    </el-form-item>
                    
                </el-form>
            </el-col>
        </el-row>
    </el-card>

    </el-card>
  </el-col>
    </el-row>

</template>
<style lang="scss" scoped>
.score-form {
    margin-left: 10px;
}

.avatar-uploader {
  margin-left: 60px;
    :deep() {
        .avatar {
            width: 500px;
            height: 300px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 500px;
            height: 300px;
            text-align: center;
        }
    }
}
/* 控制两个模块的css样式 */
.login-page {
    height: 100vh;
    background-color: #fff;

    .bg {
        background: url('@/assets/logo2.png') no-repeat left top / 150px auto,
            url('@/assets/UploadScore/left.png') no-repeat center / cover;
        border-radius: 20px 20px 20px 20px;
    }

    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .title {
            margin: 0 auto;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
}
</style>